import {
    GET_ALL_ITEM,
    DEL_TODO_ITEM,
    CHANGE_TODO_ITEM,
    ADD_TODO_ITEM,
    REMOVE_FINISHED_TODO_ITEM,
    SELECT_ALL_TODO_ITEM
} from './actionTypes'

// 默认数据
const defaultState = {
    todos: [],
    finishedCount: 0
}

export default (state = defaultState, action) => {
    // console.log(state, action)
    // 获取所有记录
    if(action.type === GET_ALL_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.todos = action.todos;
        return newState;
    }
    // 删除一条记录
    if (action.type === DEL_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        let finishedCount = 0;
        // 1、遍历
        newState.todos.forEach((todo, index) => {
            if (todo.id === action.todoId) {
                newState.todos.splice(index, 1)
            }
        })

        // 2、处理选中的
        newState.todos.forEach((todo, index) => {
            if (todo.finished) {
                finishedCount += 1;
            }
        })

        // 更新状态
        newState.finishedCount = finishedCount;
        return newState;
    }

    // 修改一条记录状态
    if (action.type === CHANGE_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        let finishedCount = 0;
        // 遍历
        newState.todos.forEach((todo, index) => {
            if (action.todoId === todo.id) {
                todo.finished = action.isFinished;
            }
            if (todo.finished) {
                finishedCount += 1;
            }
        })

        // 更新状态
        newState.finishedCount = finishedCount;
        return newState;
    }

    // 添加一条记录
    if (action.type === ADD_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.todos.push(action.todo);
        return newState;
    }

    // 删除所有已完成的记录
    if (action.type === REMOVE_FINISHED_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        let tempArr = [];
        newState.todos.forEach((todo) => {
            if (!todo.finished) {
                tempArr.push(todo);
            }
        })

        newState.todos = tempArr;
        newState.finishedCount = 0;
        return newState;
    }

    // 选中/取消全部
    if (action.type === SELECT_ALL_TODO_ITEM) {
        const newState = JSON.parse(JSON.stringify(state));
        let finishedCount = 0;
        newState.todos.forEach((todo, index) => {
            todo.finished = action.flag;
        })

        newState.todos.forEach((todo, index) => {
            if (todo.finished) {
                finishedCount += 1;
            }
        })

        newState.finishedCount = finishedCount;
        return newState;
    }
    return state
}